package cn.fengLone.pay.service.impl;

import java.security.interfaces.RSAPublicKey;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.fengLone.pay.constraint.FengPayContraint;
import cn.fengLone.pay.dao.AliPayFullDao;
import cn.fengLone.pay.dao.BillHisDao;
import cn.fengLone.pay.dao.BillHisErrorDao;
import cn.fengLone.pay.dao.PayInfoDao;
import cn.fengLone.pay.dao.PayTypeDao;
import cn.fengLone.pay.dao.PaymentDao;
import cn.fengLone.pay.dao.UnionPayBackInfoDao;
import cn.fengLone.pay.dao.UnionPayFullDao;
import cn.fengLone.pay.dao.UserDao;
import cn.fengLone.pay.dao.WebSiteDao;
import cn.fengLone.pay.dao.WeiXinFullDao;
import cn.fengLone.pay.entity.AliPayFull;
import cn.fengLone.pay.entity.BillHisErrorInfo;
import cn.fengLone.pay.entity.BillHisInfo;
import cn.fengLone.pay.entity.PayInfo;
import cn.fengLone.pay.entity.Payment;
import cn.fengLone.pay.entity.UnionPayBackInfo;
import cn.fengLone.pay.entity.UnionPayFullInfo;
import cn.fengLone.pay.entity.User;
import cn.fengLone.pay.entity.WebSite;
import cn.fengLone.pay.entity.WeiXinFull;
import cn.fengLone.pay.exception.BaseException;
import cn.fengLone.pay.service.PayService;
import cn.fengLone.pay.util.HttpsUtil;
import cn.fengLone.pay.util.SimpleUtil;
import cn.fengLone.pay.util.SpringUtil;
import cn.fengLone.pay.util.RSA.RSAUtil;
import cn.fengLone.pay.util.aliPay.AliPayUtil;
import cn.fengLone.pay.util.unionPay.UnionPayUtil;
import cn.fengLone.pay.util.wechat.WeiXinPayUtil;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * 网页支付订单处理服务层实现类
 * 
 * @author Guo Pengfei
 * 
 * @compony 深圳风轮科技有限公司
 * 
 * @date 2017-07-28
 * 
 * @site https://www.blog-china.cn
 */
@Service("payService")
@Transactional(rollbackFor=Exception.class)
public class PayServiceImpl implements PayService {
	private Logger logger = Logger.getLogger(PayService.class);
	
	@Resource
	private PayInfoDao payDao;

	@Resource
	private WebSiteDao webSiteDao;

	
	@Resource
	private PaymentDao paymentDao;
	
	@Resource
	private WeiXinFullDao weiXinFullDao;
	
	
	@Resource
	private PayInfoDao payInfoDao;
	
	@Resource
	private UserDao userDao;
	
	
	@Resource
	private PayTypeDao payTypeDao;
	
	@Resource
	private UnionPayFullDao unionPayFullDao;
	
	@Resource
	private AliPayFullDao aliPayFullDao;
	
	
	@Resource
	private BillHisDao billHisDao;
	
	@Resource
	private UnionPayBackInfoDao unionPayBackInfoDao;
	
	
	@Resource
	private BillHisErrorDao billHisErrorDao;
	
	/**
	 * 初始化订单信息
	 * 
	 * @param siteToken
	 *            站点口令
	 * @param sign_value
	 *            签名后的订单参数
	 * @return
	 */
	public Map<String, Object> initPayInfo(String siteToken, String sign_value) throws Exception{
		Map<String, Object> resultMap = invaldateKey(siteToken,sign_value);
		
		if(Integer.parseInt((String)resultMap.get("return_code"))  == 0)
			return resultMap;
		
		WebSite webSite = (WebSite) resultMap.get("webSite");
		
		String decodeData = null;
		try {
			String publicKey = webSite.getPublicKey();
//			RSAPublicKey rsaPublicKey = (RSAPublicKey) RSAUtils
//					.getPublicKey(publicKey);
//			decodeData = RSAUtils.decryptByPublicKey(rsaPublicKey, sign_value);
			decodeData = RSAUtil.decryptByPublicKey(sign_value, publicKey);
		} catch (Exception e) {
//			e.printStackTrace();
			throw new BaseException(e,false,SpringUtil.getI18nMsg("decode_val_error"));
			
//			resultMap.put("result", false);
//			resultMap.put("return_msg", SpringUtil.getI18nMsg("decode_val_error"));
//			return resultMap;
		}
		JSONObject jsonObject = null;
		try {
			jsonObject = JSONObject.parseObject(decodeData);
		} catch (Exception e) {
			throw new BaseException(e,false,SpringUtil.getI18nMsg("decode_val_error"));
			
//			
//			e.printStackTrace();
//			resultMap.put("result", false);
//			resultMap.put("return_msg", SpringUtil.getI18nMsg("decode_val_error"));
//			return resultMap;
		}
		String order_id = jsonObject.getString("order_id");
		String total_pay = jsonObject.getString("total_pay");
		String order_name = jsonObject.getString("order_name");
		String payee = jsonObject.getString("payee");
		resultMap.put("order_id", order_id);
		resultMap.put("total_pay", total_pay);
		resultMap.put("order_name", order_name);
		resultMap.put("payee", payee);
		resultMap.put("result", true);
		return resultMap;
	}

	/**
	 * 微信扫码支付订单
	 * 
	 * 逻辑：
	 * 
	 * 1、校验siteToken是否存在,审核状态
	 * 2、校验签名数据
	 * 3、根据第三方系统订单和siteToken查询平台订单是否存在-存在个检查时间是否超出支付的有效时间，超时返回错误信息
	 * 4、根据PM（固定）+当前时间(20170802151022)+siteToken 的格式生成本平台的订单
	 * 5、保存订单到订单表
	 * 6、使用微信SDK调用微信支付统一下单接口，接收返回的数据
	 * 7、将收到的二维码链接、和使用公钥加密的用户siteToken,一起返回给第三方系统
	 * 
	 * @param siteToken
	 *            站点口令
	 * @param sign_value
	 *            签名后的订单参数
	 * @return
	 */
	@SuppressWarnings("unused")
	public Map<String, String> wechatSaoPay(String siteToken, String sign_value) 
			throws Exception{
		
		Map<String, String> serviceMap = new HashMap<String,String>();
		
		Map<String, Object> resultMap = invaldateKey(siteToken,sign_value);
		
		if(Integer.parseInt((String)resultMap.get("return_code"))  == 0){
			serviceMap.put("return_code", "0");
			serviceMap.put("return_msg", (String)resultMap.get("return_msg"));
			return serviceMap;
		}
		
		WebSite webSite = (WebSite) resultMap.get("webSite");
		
		String decodeData = null;
		try {
			//获取接入站点的公钥
			String publicKey = webSite.getPublicKey();
			//解密站点发送的订单
			decodeData = RSAUtil.decryptByPublicKey(sign_value, publicKey);
		} catch (Exception e) {
			throw new BaseException(e,false,SpringUtil.getI18nMsg("decode_val_error"));
		}
		JSONObject jsonObject = null;
		try {
			//将字符串转为Json
			jsonObject = JSONObject.parseObject(decodeData);
		} catch (Exception e) {
			throw new BaseException(e,false,SpringUtil.getI18nMsg("decode_val_error"));
		}
		String order_id = jsonObject.getString("order_id");  //订单号
		String total_pay = jsonObject.getString("total_pay");//总金额
		String order_name = jsonObject.getString("order_name"); //订单描述
//		String payee = jsonObject.getString("payee");  //收款人
		String order_detail = jsonObject.getString("order_detail"); //订单详情
//		String payType = jsonObject.getString("payType"); //支付类型
		String product_id = jsonObject.getString("product_id");
		//2、校验签名数据，参数是否漏传
		if(isEmpty(order_id) || isEmpty(total_pay) ||isEmpty(order_name) || isEmpty(product_id)){
			serviceMap.put("return_code", "0");
			serviceMap.put("return_msg", SpringUtil.getI18nMsg("decode_val_error")+",参数可能漏传");
			return serviceMap;
		}
		//3、获取网站发起的支付方式是否已经接入
		Payment payment = paymentDao.queryPaymentBySiteIdAndPayType(webSite.getId(), FengPayContraint.WECHART_SAO);
		if(payment == null){
			serviceMap.put("return_code", "0");
			serviceMap.put("return_msg", SpringUtil.getI18nMsg("no_pay_type"));
			return serviceMap;
		}
		
		WeiXinFull  weiXinFull = null;
		//判断用户的支付方式接入是否使用的营业执照
		if(payment.getIsFullInfo() == '1'){
			//非营业执照接入，启动代理收款模式
//			weiXinFull = weiXinFullDao.queryWeiXinFullById(1);   ///加载本平台通过营业执照申请到的公钥私钥信息
			String appID = SimpleUtil.wechatPayMap.get("appID");
			String mchID = SimpleUtil.wechatPayMap.get("mchID");
			String certPath = SimpleUtil.wechatPayMap.get("certPath");
			String mchKey = SimpleUtil.wechatPayMap.get("mchKey");
			weiXinFull = new WeiXinFull();
			weiXinFull.setAppID(appID);
			weiXinFull.setMchID(mchID);
			weiXinFull.setMchKey(mchKey);
			weiXinFull.setCertPath(certPath);
		}else
			weiXinFull = weiXinFullDao.queryWeiXinFullBySiteId(webSite.getId(),FengPayContraint.WECHART_SAO);
		
		PayInfo payInfo = payInfoDao.queryPayInfoByMertradeNum(order_id,siteToken);
		
		if(payInfo ==null){
			//这个订单为第一次发起
			Date date = new Date();
			payInfo = new PayInfo();
			payInfo.setWebSite(webSite);
			payInfo.setTradeNum(SimpleUtil.getTradeNum());
			payInfo.setPayType(FengPayContraint.WECHART_SAO);
			payInfo.setMertradeNum(order_id);
			payInfo.setSubject(order_name);
			payInfo.setDetail(order_detail);
			payInfo.setTotal_fee(total_pay);
			payInfo.setSpbill_create_ip(SimpleUtil.getMyIp());
			payInfo.setTradeId(product_id);
			payInfo.setPayResult('1');
			payInfo.setChannelType("");//微信不需要传入此参数
			payInfo.setCreateTime(new Timestamp(date.getTime()));
			payInfo.setNotifyResult(0);
			payInfoDao.addPayInfo(payInfo);
		}else{
			//该订单已经存在于本系统中
			Timestamp currentTime = new Timestamp(new Date().getTime());
			Timestamp createTime = payInfo.getCreateTime();
			long timeResult = (currentTime.getTime() - createTime.getTime())/(1000*60); //两个timestamp得到毫秒数并相减，然后除以60000
			if(timeResult>20){
				//超过20分钟没有支付
				serviceMap.put("return_code", "0");
				serviceMap.put("return_msg", SpringUtil.getI18nMsg("pay_time_pass"));
				return serviceMap;
			}
			if(payInfo.getPayResult() !='1'){
				//订单已经结束
				serviceMap.put("return_code", "0");
				serviceMap.put("return_msg", SpringUtil.getI18nMsg("pay_over"));
				return serviceMap;
			}
			//订单已经被提交过，且在支付时间范围内，而且订单状态为未支付状态，则更新订单信息（第三方系统中的用户可能更新了商品的数量、支付方式等）
//			payInfo.setWebSite(webSite);
//			payInfo.setTradeNum(SimpleUtil.getTradeNum(siteToken));
			payInfo.setPayType(FengPayContraint.WECHART_SAO);
//			payInfo.setMertradeNum(order_id);
			payInfo.setSubject(order_name);
			payInfo.setDetail(order_detail);
			payInfo.setTotal_fee(total_pay);
//			payInfo.setSpbill_create_ip(SimpleUtil.getMyIp());
			payInfo.setTradeId(product_id);
			payInfo.setPayResult('1');
			payInfo.setChannelType("");//微信不需要传入此参数
			payInfoDao.updatePayInfo(payInfo);
		}
		
		Map<String, String> map = WeiXinPayUtil.payOrder(weiXinFull, payInfo);
		if(map.get("result_code").equals("SUCCESS")){
			String qrCode = map.get("code_url");
			RSAPublicKey publicKey = null;
			try {
				Map<String, String> paramMap = new HashMap<String, String>();
				siteToken = RSAUtil.encryptByPublicKey(siteToken, webSite.getPublicKey());
				qrCode = RSAUtil.encryptByPublicKey(qrCode, webSite.getPublicKey());
				serviceMap.put("qrCode", qrCode);
				serviceMap.put("siteToken", siteToken);
				serviceMap.put("return_code", "1");
			} catch (Exception e) {
				throw new BaseException(e,false,SpringUtil.getI18nMsg("pay_result_encode_error"));
			}
		}
		return serviceMap;
	}
	/**
	 * 微信App支付订单
	 * @param siteToken  站点口令
	 * @param sign_value  签名后的订单参数
	 * @return
	 */
	public Map<String, Object> wechatAppPay(String siteToken, String sign_value)
			throws Exception{
		
		Map<String, Object> resultMap = invaldateKey(siteToken,sign_value);
		
		if(Integer.parseInt((String)resultMap.get("return_code"))  == 0)
			return resultMap;
		
		WebSite webSite = (WebSite) resultMap.get("webSite");
		
		String decodeData = null;
		try {
			String publicKey = webSite.getPublicKey();
			decodeData = RSAUtil.decryptByPublicKey(sign_value, publicKey);
			
		} catch (Exception e) {
			throw new BaseException(e,false,SpringUtil.getI18nMsg("decode_val_error"));
			
			
//			e.printStackTrace();
//			resultMap.put("return_code", 0);
//			resultMap.put("return_msg", SpringUtil.getI18nMsg("decode_val_error"));
//			return resultMap;
		}
		JSONObject jsonObject = null;
		try {
			jsonObject = JSONObject.parseObject(decodeData);
		} catch (Exception e) {
			throw new BaseException(e,false,SpringUtil.getI18nMsg("decode_val_error"));
			
			
//			e.printStackTrace();
//			resultMap.put("return_code", 0);
//			resultMap.put("return_msg", SpringUtil.getI18nMsg("decode_val_error"));
//			return resultMap;
		}
		String order_id = jsonObject.getString("order_id");  //接入系统的订单号
		String total_pay = jsonObject.getString("total_pay");//应付金额
		String order_name = jsonObject.getString("order_name"); //APP名称-商品名称
		String client_ip = jsonObject.getString("client_ip"); //客户端实际IP
		String order_detail = jsonObject.getString("order_detail"); //客户端实际IP
		
		//2、校验签名数据，参数是否漏传
		if(isEmpty(order_id) || isEmpty(total_pay) ||isEmpty(order_name) ||isEmpty(client_ip)){
			resultMap.put("return_code", 0);
			resultMap.put("return_msg", SpringUtil.getI18nMsg("decode_val_error"));
			return resultMap;
		}
		//3、获取网站发起的支付方式是否已经接入
		Payment payment = paymentDao.queryPaymentBySiteIdAndPayType(webSite.getId(), "");
		if(payment == null){
			resultMap.put("return_code", 0);
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_pay_type"));
			return resultMap;
		}
		
		WeiXinFull  weiXinFull = null;
		//判断用户的支付方式接入是否使用的营业执照
		if(payment.getIsFullInfo() == '1')
			//非营业执照接入，启动代理收款模式
			weiXinFull = weiXinFullDao.queryWeiXinFullById(1);   ///加载本平台通过营业执照申请到的公钥私钥信息
		else
			weiXinFull = weiXinFullDao.queryWeiXinFullBySiteId(webSite.getId(),FengPayContraint.WECHART_APP);
		
		PayInfo payInfo = payInfoDao.queryPayInfoByMertradeNum(order_id,siteToken);
		
		if(payInfo ==null){
			//这个订单为第一次发起
			Date date = new Date();
			payInfo = new PayInfo();
			payInfo.setWebSite(webSite);
			payInfo.setTradeNum(SimpleUtil.getTradeNum());
			payInfo.setPayType(FengPayContraint.WECHART_APP);
			payInfo.setMertradeNum(order_id);
			payInfo.setSubject(order_name);
			payInfo.setDetail(order_detail == null?"":order_detail);
			payInfo.setTotal_fee(total_pay);
			payInfo.setSpbill_create_ip(SimpleUtil.getMyIp());
			payInfo.setTradeId("");
			payInfo.setPayResult('1');
			payInfo.setCreateTime(new Timestamp(date.getTime()));
			payInfo.setNotifyResult(0);
			payInfoDao.addPayInfo(payInfo);
		}else{
			//该订单已经存在于本系统中
			Timestamp currentTime = new Timestamp(new Date().getTime());
			Timestamp createTime = payInfo.getCreateTime();
			long timeResult = (currentTime.getTime() - createTime.getTime())/(1000*60); //两个timestamp得到毫秒数并相减，然后除以60000
			if(timeResult>20){
				//超过20分钟没有支付
				resultMap.put("return_code", 0);
				resultMap.put("return_msg", SpringUtil.getI18nMsg("pay_time_pass"));
				return resultMap;
			}
			if(payInfo.getPayResult() !='1'){
				//订单已经结束
				resultMap.put("return_code", 0);
				resultMap.put("return_msg", SpringUtil.getI18nMsg("pay_over"));
				return resultMap;
			}
			//订单已经被提交过，且在支付时间范围内，而且订单状态为未支付状态，则更新订单信息（第三方系统中的用户可能更新了商品的数量、支付方式等）
//			
			payInfo.setPayType(FengPayContraint.WECHART_APP);
			payInfo.setSubject(order_name);
			payInfo.setDetail(order_detail == null?"":order_detail);
			payInfo.setTotal_fee(total_pay);
			payInfo.setTradeId("");
			payInfo.setPayResult('1');
			payInfo.setWebSite(webSite);
			payInfo.setMertradeNum(order_id);
			payInfo.setSpbill_create_ip(SimpleUtil.getMyIp());
			payInfo.setTradeNum(SimpleUtil.getTradeNum());
//			
			payInfoDao.updatePayInfo(payInfo);
		}
		Map<String, String> map = WeiXinPayUtil.payOrder(weiXinFull, payInfo);
		
		
		if(map.get("return_code") == "1"){
			String qrCode = map.get("code_url");
			try {
				qrCode = RSAUtil.encryptByPublicKey(qrCode,webSite.getPublicKey() );
				siteToken = RSAUtil.encryptByPublicKey(siteToken,webSite.getPublicKey() );
				
				
				String appid=map.get("appid");//微信开放平台审核通过的应用APPID
				String partnerid=map.get("partnerid");//商户号
				String prepayid=map.get("prepayid");//微信返回的支付交易会话ID
				String noncestr=map.get("noncestr");//随机字符串
				String signValue=map.get("signValue");//接口返回的支付信息，微信SDK已签名
				if(appid!=null && !appid.equals("") && partnerid!=null && !partnerid.equals("") && prepayid!=null && !prepayid.equals("") && noncestr!=null && !noncestr.equals("") && signValue!=null && !signValue.equals("")){
					
					resultMap.put("appid", appid);
					resultMap.put("partnerid", partnerid);
					resultMap.put("prepayid", prepayid);
					resultMap.put("package", "Sign=WXPay");
					resultMap.put("noncestr", noncestr);
					resultMap.put("timestamp", noncestr);
					
					resultMap.put("sign", signValue);
					resultMap.put("return_code", 1);
					resultMap.put("qrCode", qrCode);
					resultMap.put("siteToken", siteToken);
					
					
				}else{
					resultMap.put("return_code", 0);
					resultMap.put("return_msg", SpringUtil.getI18nMsg("return_msg"));
				}
			} catch (Exception e) {
				throw new BaseException(e,false,SpringUtil.getI18nMsg("return_msg"));
				
				
				// TODO Auto-generated catch block
//				e.printStackTrace();
//				resultMap.put("return_code", 0);
//				resultMap.put("return_msg", SpringUtil.getI18nMsg("return_msg"));
//				return resultMap;
			}
			
		}
		return resultMap;
	}
	/**
	 * 判断字符串是否为空
	 * @param str
	 * @return
	 */
	private boolean isEmpty(String str){
		return str==null||str.trim().equals("");
	}

	public boolean testAddTwoData() throws Exception{
		Date date = new Date();
		User user = userDao.findUserById(1);
		
		
		WebSite webSite = new WebSite();
		webSite.setId(11111);
		webSite.setFunds(1223);
		webSite.setSiteName("测试");
		webSite.setSiteUrl("www.blog-china.cn");
		webSite.setUser(user);
		webSite.setSiteToken("SDFHSKJ23NSKDJFJ");
		webSite.setVerifyType('1');
		webSite.setVerifyMsg("通过");
		webSite.setPublicKey("sdflksdjfslkljdfsdoisdhfskdjfsdklfjkl");
		webSite.setPrivateKey("LKSJDFSDYUIY345345ISDFSDFHSUYUWE6WE76ESDFSD9FDS");
		webSite.setCreateTime(new Timestamp(date.getTime()));
		webSite.setFunds(12212);
		try {
			webSiteDao.saveWebSite(webSite);
			System.out.println("第一个成功");
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException(false,"新增站点失败....");
			// TODO: handle exception
		}
		System.out.println(webSite.getId());
		
		PayInfo  payInfo = null;
		payInfo = new PayInfo();
		payInfo.setWebSite(webSite);
		payInfo.setTradeNum("SDFSDFLLK232938");
		payInfo.setPayType(FengPayContraint.WECHART_APP);
		payInfo.setMertradeNum("201455124551EM");
		payInfo.setSubject("藐视");
		payInfo.setDetail("测试商品");
		payInfo.setTotal_fee("1000");
		payInfo.setPaymsg("sdfsd");
		payInfo.setSpbill_create_ip(SimpleUtil.getMyIp());
		payInfo.setTradeId("");
		payInfo.setPayResult('1');
		payInfo.setNotifyResult(0);
		payInfo.setCreateTime(new Timestamp(date.getTime()));
		try {
			payInfoDao.addPayInfo(payInfo);
			System.out.println("第二个成功....");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("第二个失败!");
			throw new BaseException(false,"新增订单失败....");
		}
		
		return true;
	}
	/**
	 * 银联B2C网关支付订单处理
	 * 
	 * @param siteToken
	 *            站点口令
	 * @param sign_value
	 *            签名后的订单参数
	 * @return
	 */
	public Map<String, Object> b2CGateWayPay(String siteToken, String sign_value)
			throws Exception {

		Map<String, Object> resultMap = invaldateKey(siteToken,sign_value);
				
		if(Integer.parseInt((String)resultMap.get("return_code"))  == 0)
			return resultMap;
		
		WebSite webSite = (WebSite) resultMap.get("webSite");
		
		String decodeData = null;
		try {
			// 获取接入站点的公钥
			String publicKey = webSite.getPublicKey();
			// 解密站点发送的订单
			decodeData = RSAUtil.decryptByPublicKey(sign_value, publicKey);
		} catch (Exception e) {
			throw new BaseException(e, false,
					SpringUtil.getI18nMsg("decode_val_error"));
		}
		JSONObject jsonObject = null;
		try {
			// 将字符串转为Json
			jsonObject = JSONObject.parseObject(decodeData);
		} catch (Exception e) {
			throw new BaseException(e, false,
					SpringUtil.getI18nMsg("decode_val_error"));
		}
		String order_id = jsonObject.getString("order_id"); // 订单号
		String total_pay = jsonObject.getString("total_pay");// 总金额
		String order_name = jsonObject.getString("order_name"); // 订单描述
		String payee = jsonObject.getString("payee"); // 收款人
		String order_detail = jsonObject.getString("order_detail"); // 订单详情
		// String payType = jsonObject.getString("payType"); //支付类型
		String product_id = jsonObject.getString("product_id");
		String channelType = jsonObject.getString("hannelType");
		// 2、校验签名数据，参数是否漏传
		if (isEmpty(order_id) || isEmpty(total_pay) || isEmpty(order_name)
				|| isEmpty(payee) || isEmpty(channelType)) {
			resultMap.put("return_code", 0);
			resultMap.put("return_msg",
					SpringUtil.getI18nMsg("decode_val_error"));
			return resultMap;
		}
		// 3、获取网站发起的支付方式是否已经接入
		Payment payment = paymentDao.queryPaymentBySiteIdAndPayType(
				webSite.getId(), FengPayContraint.B2C_GATEWAY);
		if (payment == null) {
			resultMap.put("return_code", 0);
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_pay_type"));
			return resultMap;
		}

		UnionPayFullInfo unionPayFullInfo = null;
		// 判断用户的支付方式接入是否使用的营业执照
		if (payment.getIsFullInfo() == '1') {
			// 非营业执照接入，启动代理收款模式
			// ///加载本平台通过营业执照申请到的公钥私钥信息
			String mchID = SimpleUtil.b2CGateWayMap.get("mchID");
			String certPath = SimpleUtil.b2CGateWayMap.get("certPath");
			String mchKey = SimpleUtil.b2CGateWayMap.get("mchKey");

			unionPayFullInfo = new UnionPayFullInfo();
			unionPayFullInfo.setMchID(mchID);
			unionPayFullInfo.setMchKey(mchKey);
			unionPayFullInfo.setCertPath(certPath);

		} else
			unionPayFullInfo = unionPayFullDao.queryUnionPayFullBySiteId(webSite.getId());

		PayInfo payInfo = payInfoDao.queryPayInfoByMertradeNum(order_id,
				siteToken);

		if (payInfo == null) {
			// 这个订单为第一次发起
			Date date = new Date();
			payInfo = new PayInfo();
			payInfo.setWebSite(webSite);
			payInfo.setTradeNum(SimpleUtil.getTradeNum());
			payInfo.setPayType(FengPayContraint.B2C_GATEWAY);
			payInfo.setMertradeNum(order_id);
			payInfo.setSubject(order_name);
			payInfo.setDetail(order_detail);
			payInfo.setTotal_fee(total_pay);
			payInfo.setSpbill_create_ip(SimpleUtil.getMyIp());
			payInfo.setTradeId(product_id);
			payInfo.setPayResult('1');
			payInfo.setChannelType(channelType);
			payInfo.setCreateTime(new Timestamp(date.getTime()));
			payInfo.setNotifyResult(0);
			payInfoDao.addPayInfo(payInfo);
		} else {
			// 该订单已经存在于本系统中
			Timestamp currentTime = new Timestamp(new Date().getTime());
			Timestamp createTime = payInfo.getCreateTime();
			long timeResult = (currentTime.getTime() - createTime.getTime())
					/ (1000 * 60); // 两个timestamp得到毫秒数并相减，然后除以60000
			if (timeResult > 20) {
				// 超过20分钟没有支付
				resultMap.put("return_code", 0);
				resultMap.put("return_msg",
						SpringUtil.getI18nMsg("pay_time_pass"));
				return resultMap;
			}
			if (payInfo.getPayResult() != '1') {
				// 订单已经结束
				resultMap.put("return_code", 0);
				resultMap.put("return_msg", SpringUtil.getI18nMsg("pay_over"));
				return resultMap;
			}
			// 订单已经被提交过，且在支付时间范围内，而且订单状态为未支付状态，则更新订单信息（第三方系统中的用户可能更新了商品的数量、支付方式等）
			// payInfo.setWebSite(webSite);
			// payInfo.setTradeNum(SimpleUtil.getTradeNum(siteToken));
			payInfo.setPayType(FengPayContraint.B2C_GATEWAY);
			// payInfo.setMertradeNum(order_id);
			payInfo.setSubject(order_name);
			payInfo.setDetail(order_detail);
			payInfo.setTotal_fee(total_pay);
			// payInfo.setSpbill_create_ip(SimpleUtil.getMyIp());
			payInfo.setTradeId(product_id);
			payInfo.setPayResult('1');
			payInfo.setChannelType(channelType);
			
			payInfoDao.updatePayInfo(payInfo);
		}
		String formHtml = null;
		try {
			formHtml = UnionPayUtil.B2CGateWayPay( unionPayFullInfo, payInfo);
		} catch (Exception e) {
			throw new BaseException(e,false,SpringUtil.getI18nMsg("uniPay_order_error"));
		}
		RSAPublicKey publicKey = null;
		
		try {

			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("siteToken", siteToken);

			String signValue = RSAUtil.encryptByPublicKey(paramMap, webSite.getPublicKey());
			formHtml = RSAUtil.encryptByPublicKey(formHtml, webSite.getPublicKey());

			resultMap.put("return_code", 1);
			resultMap.put("siteToken", signValue);
			resultMap.put("order_form", formHtml);
			
		} catch (Exception e) {
			throw new BaseException(e, false,
					SpringUtil.getI18nMsg("pay_result_encode_error"));
		}
		return resultMap;
	}
	
	/**
	 * 校验传入的关键参数是否正确
	 * @param siteToken  站点口令
	 * @return
	 */
	private Map<String, Object> invaldateKey(String siteToken,String sign_value ) throws Exception{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		WebSite webSite = webSiteDao.querySite(siteToken);
		// 1、校验siteToken是否存在
		if (webSite == null) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_site"));
			return resultMap;
		}
		// 1、审核状态
		if (webSite.getVerifyType() != '3') {
			// 网站没审核没有通过
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("site_no_pass"));
			return resultMap;
		}
		
		// 2、校验签名数据是否为空
		if (sign_value == null || sign_value.trim().equals("")) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_sign_val"));
			return resultMap;
		}

		resultMap.put("webSite", webSite);
		resultMap.put("return_code", "1");
		return resultMap;
	}
	
	/**
	 * 撤销银联支付订单
	 * @param siteToken  站点口令
	 * @param sign_value  加密后的订单id
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> B2CGateWayRevoke(String siteToken,String sign_value)throws Exception{
		Map<String, String> resultMap = new HashMap<String, String>();
		
		Map<String, Object> temptMap = invaldateKey(siteToken,sign_value);
		
		if(Integer.parseInt((String)resultMap.get("return_code"))  == 0){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", (String)temptMap.get("return_msg"));
			return resultMap;
		}
		
		JSONObject jsonObject = null;
		try {
			// 将字符串转为Json
			jsonObject = JSONObject.parseObject(sign_value);
		} catch (Exception e) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", 
					SpringUtil.getI18nMsg("decode_val_error"));
			return resultMap;
		}
		String order_id = jsonObject.getString("order_id"); // 订单号
		PayInfo payInfo = payInfoDao.queryPayInfoByMertradeNum(order_id,
				siteToken);

		if(payInfo == null){
			//没有找到要撤销的订单
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_order_error"));
			return resultMap;
		}
		
		
		String payType = payInfo.getPayType();//判断支付方式是否是银联支付
		if(!payType.trim().equals("000201")){
			//不是银联网关支付
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("order_PC_error"));
			return resultMap;
		}
		
		// 3、获取网站发起的支付方式是否已经接入
		Payment payment = paymentDao.queryPaymentBySiteIdAndPayType(
				payInfo.getWebSite().getId(), FengPayContraint.B2C_GATEWAY);
		if (payment == null) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_pay_type"));
			return resultMap;
		}

		UnionPayFullInfo unionPayFullInfo = null;
		// 判断用户的支付方式接入是否使用的营业执照
		if (payment.getIsFullInfo() == '1') {
			// 非营业执照接入，启动代理收款模式
			// ///加载本平台通过营业执照申请到的公钥私钥信息
			String mchID = SimpleUtil.b2CGateWayMap.get("mchID");
			String certPath = SimpleUtil.b2CGateWayMap.get("certPath");
			String mchKey = SimpleUtil.b2CGateWayMap.get("mchKey");

			unionPayFullInfo = new UnionPayFullInfo();
			unionPayFullInfo.setMchID(mchID);
			unionPayFullInfo.setMchKey(mchKey);
			unionPayFullInfo.setCertPath(certPath);
		} else
			unionPayFullInfo = unionPayFullDao.queryUnionPayFullBySiteId(payInfo.getWebSite().getId());
		//初始化退款订单信息
		UnionPayBackInfo unionPayBackInfo =initOrderBackInfo(payInfo);
		
		Map<String, String> temptMap2 =  UnionPayUtil.B2CGateWayRevoke(unionPayFullInfo,unionPayBackInfo,payInfo.getPayType(),payInfo.getChannelType());
		
		String return_code = temptMap2.get("return_code");
		if(return_code.equals("1")){
			//撤销命令执行成功，但是并不表示资金返还，需要查询状态
			unionPayBackInfoDao.addUnionPayBackInfo(unionPayBackInfo);
			payInfo.setPayResult('8');
			payInfo.setPaymsg("退款中");
			payInfo.setQueryId("");
			payInfoDao.updatePayResult(payInfo);
			
			resultMap.put("return_code", "1");
			
		}else{
			//失败，或者状态未明确
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", temptMap2.get("return_msg"));
		}
		String publicKey = payInfo.getWebSite().getPublicKey();
		
		resultMap.put("siteToken", RSAUtil.encryptByPublicKey(siteToken, publicKey));
		
		return resultMap;
	}
	/**
	 * 初始化一个退款订单
	 * @param payInfo
	 * @return
	 */
	private UnionPayBackInfo initOrderBackInfo(PayInfo payInfo){
		UnionPayBackInfo unionPayBackInfo = new UnionPayBackInfo();
		unionPayBackInfo.setBackCreateTime(payInfo.getCreateTime());
		unionPayBackInfo.setBackQueryId(payInfo.getQueryId());
		unionPayBackInfo.setBackTradeNum(payInfo.getTradeNum());
		unionPayBackInfo.setCreateTime(new Timestamp(new Date().getTime()));
		unionPayBackInfo.setMertradeNum(payInfo.getMertradeNum());
		unionPayBackInfo.setPaymsg("");
		unionPayBackInfo.setPayResult('1');
//		unionPayBackInfo.setQueryId("");
		unionPayBackInfo.setResultTime(null);
		unionPayBackInfo.setTotal_fee(payInfo.getTotal_fee());
		unionPayBackInfo.setTradeNum(payInfo.getTradeNum()+"BACK");
		unionPayBackInfo.setWebSite(payInfo.getWebSite());
		
		return unionPayBackInfo;
	}
	
	
	/**
	 *银联支付全网交易状态查询,由于银联支付订单和撤销订单不是同一个订单号，
	 *因此需要查询订单表和撤销订单信息表，同步确认该订单是什么状态
	 * @param siteToken  站点口令
	 * @param sign_value  加密后的订单id
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> b2CGateWayPayQuery(String siteToken,
			String sign_value) throws Exception {
		Map<String, String> resultMap = new HashMap<String, String>();

		WebSite webSite = webSiteDao.querySite(siteToken);
		//1、校验siteToken是否存在
		if (webSite == null) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_site"));
			return resultMap;
		}
		//1、审核状态
		if(webSite.getVerifyType() !='3'){
			//网站没审核没有通过
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("site_no_pass"));
			return resultMap;
		}
		
		//2、校验签名数据是否为空
		if (sign_value == null || sign_value.trim().equals("")) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_sign_val"));
			return resultMap;
		}
		String decodeData = null;
		String publicKey  =null;
		try {
			//获取接入站点的公钥
			publicKey = webSite.getPublicKey();
			//解密站点发送的订单
			decodeData = RSAUtil.decryptByPublicKey(sign_value,publicKey);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException(e,false,SpringUtil.getI18nMsg("decode_val_error"));
		}
		JSONObject jsonObject = null;
		try {
			//将字符串转为Json
			jsonObject = JSONObject.parseObject(decodeData);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException(e,false,SpringUtil.getI18nMsg("decode_val_error"));
		}
		JSONArray  orderIds  = null;
		try {
			 orderIds = jsonObject.getJSONArray("order_ids");
		} catch (Exception e) {
			logger.error("return_msg\t:"+SpringUtil.getI18nMsg("out_orderIds_error"));
			e.printStackTrace();
			throw new BaseException(e,false,SpringUtil.getI18nMsg("out_orderIds_error"));
		}
		JSONArray jsonArray = new JSONArray();
		PayInfo payInfo =null;
		UnionPayBackInfo unionPayBackInfo = null;
		JSONObject tempJsonObject = null;
		for (int i = 0; i < orderIds.size(); i++) {
			String mertradeNum = orderIds.getString(i);
			payInfo = payInfoDao.queryPayInfoByMertradeNum(mertradeNum, siteToken);
			if(payInfo == null){
				//没有查询到订单
				tempJsonObject = new JSONObject();
				tempJsonObject.put("order_num", mertradeNum);
				tempJsonObject.put("result_code", 0+"");//错误
				tempJsonObject.put("result_msg", SpringUtil.getI18nMsg("no_order_error"));
				jsonArray.add(tempJsonObject);
				continue;
			}
			String payType = payInfo.getPayType();//支付方式
			//支付方式不是银联支付
			if(!payType.equals("000201") ||!payType.equals("000202") ){
				tempJsonObject = new JSONObject();
				tempJsonObject.put("order_num", payInfo.getMertradeNum());
				tempJsonObject.put("result_code", 0+"");//失败
				tempJsonObject.put("result_msg", SpringUtil.getI18nMsg("not_unionPay_order"));//
				jsonArray.add(tempJsonObject);
				continue;
			}
			if(payInfo.getPayResult()== '2' || payInfo.getPayResult()== '3' || payInfo.getPayResult() == '4'|| payInfo.getPayResult() == '5'){
				//本平台中此订单的支付状态已经改变了，不再查询
				tempJsonObject = new JSONObject();
//				tempMap = new HashMap<String, String>();
				tempJsonObject.put("order_num", payInfo.getMertradeNum());
				tempJsonObject.put("result_code", 1+"");//成功
				tempJsonObject.put("payResult", SimpleUtil.getPayResultDe(payInfo.getPayResult()));//成功
				jsonArray.add(tempJsonObject);
				continue;
			}
			UnionPayFullInfo unionPayFullInfo = null;
			unionPayFullInfo = initUnionPay(unionPayFullInfo, payInfo);

			unionPayBackInfo = unionPayBackInfoDao.queryPayInfoByMertradeNum(mertradeNum, siteToken);
			if(payInfo.getPayResult()== '8' ){
				//本平台中此订单为退款订单，且在退款中，需要查找银联支付插销订单信息表，然后根据订单信息表中的信息去查询撤销结果
				if(unionPayBackInfo == null){
					tempJsonObject = new JSONObject();
					tempJsonObject.put("order_num", payInfo.getMertradeNum());
					tempJsonObject.put("result_code", 0+"");//失败
					tempJsonObject.put("result_msg", SpringUtil.getI18nMsg("unionPay_back_noOrder"));//
					jsonArray.add(tempJsonObject);
					continue;
				}
				PayInfo tempPayInfo = new PayInfo();
				tempPayInfo.setPayType(payInfo.getPayType());
				tempPayInfo.setTradeNum(unionPayBackInfo.getTradeNum());
				tempPayInfo.setCreateTime(unionPayBackInfo.getCreateTime());
				
				Map<String, String> tempResultMap = UnionPayUtil.queryOrder(unionPayFullInfo, tempPayInfo);
				String result_code = tempResultMap.get("recode_code");
				if(result_code.trim().equals("SUCCESS")){
					//修改订单/撤销订单状态为已退款（撤销）
					payInfo.setPayResult('5'); //已撤销
					unionPayBackInfo.setPayResult('1');
					payInfoDao.updatePayInfo(payInfo);
					
					unionPayBackInfo.setPayResult('1');
					unionPayBackInfo.setPaymsg("");
					unionPayBackInfo.setQueryId(tempResultMap.get("queryId"));
					
					unionPayBackInfoDao.updatePayBackInfo(unionPayBackInfo);
					
					//返回订单结果
					tempJsonObject = new JSONObject();
					tempJsonObject.put("order_num", payInfo.getMertradeNum());
					tempJsonObject.put("result_code", 1+"");//成功
					tempJsonObject.put("payResult", SimpleUtil.getPayResultDe(payInfo.getPayResult()));//
					jsonArray.add(tempJsonObject);
				}else{
					//检查状态失败，直接返回返回
					tempJsonObject = new JSONObject();
					tempJsonObject.put("order_num", payInfo.getMertradeNum());
					tempJsonObject.put("result_code", 0+"");//失败
					tempJsonObject.put("result_msg", SpringUtil.getI18nMsg("order_result_no"));//
					jsonArray.add(tempJsonObject);
				}
				
			}else if(payInfo.getPayResult()== '1' ){
				//正在支付中,需要查询订单支付状态，然后修改订单表，最后返回给用户
				Map<String, String> tempResultMap = UnionPayUtil.queryOrder(unionPayFullInfo, payInfo);
				String result_code = tempResultMap.get("recode_code");
				if(result_code.trim().equals("SUCCESS")){
					payInfo.setPayResult('2'); //支付成功
					payInfo.setPaymsg("成功");
					payInfo.setQueryId(tempResultMap.get("queryId"));
					payInfoDao.updatePayResult(payInfo);
					// 保存对账信息
					String out_trade_no = tempResultMap.get("orderId"); //内部交易订单号
					BillHisInfo billHisInfo = billHisDao
							.queryBillByTradeNum(out_trade_no);
					if (billHisInfo == null) {
						billHisInfo =  new BillHisInfo();
						billHisInfo.setPayId(payInfo.getId());
						billHisInfo.setPayType(payInfo.getPayType());
						billHisInfo.setSiteId(payInfo.getWebSite().getId());
						billHisInfo.setTradeNum(out_trade_no);
						billHisInfo.setBillType('2');// 异步通知
						billHisInfo.setBillResult(tempResultMap.get("recode_code").equals(
								"SUCCESS") ? '2' : '3');
						billHisInfo
								.setBillMsg(tempResultMap.get("recode_code").equals("SUCCESS") ? tempResultMap
										.get("recode_code")
										+ "-------"
										+ tempResultMap.get("recode_msg") : "");
						billHisInfo.setCreateTime(new Timestamp(new Date().getTime()));
						billHisInfo.setResultTime(null);  //银联支付没有订单结束时间
	
						billHisDao.addBillHis(billHisInfo);
					}
					
					tempJsonObject = new JSONObject();
					tempJsonObject.put("order_num", payInfo.getMertradeNum());
					tempJsonObject.put("result_code", 1+"");//成功
					tempJsonObject.put("payResult", SimpleUtil.getPayResultDe(payInfo.getPayResult()));//
					jsonArray.add(tempJsonObject);
				}else{
					//查询支付状态失败，需要再次查询
					tempJsonObject = new JSONObject();
					tempJsonObject.put("order_num", payInfo.getMertradeNum());
					tempJsonObject.put("result_code", 0+"");//失败
					tempJsonObject.put("result_msg", SpringUtil.getI18nMsg("order_result_no"));//
					jsonArray.add(tempJsonObject);
				}
			}
		}
		resultMap.put("return_code", "1");//成功
		String sign_val = RSAUtil.encryptByPublicKey(jsonArray.toJSONString(), webSite.getPublicKey());
		resultMap.put("respContent", sign_val);
		return resultMap;
	}
	/**
	 * 检查银联支付支付结果
	 * @param jsonArray  支付结果集合
	 * @param unionPayFullInfo  银联支付配置信息
	 * @param payInfo  订单
	 * @throws Exception 异常
	 */
	private void checkUnionPayType(JSONArray jsonArray,
			UnionPayFullInfo unionPayFullInfo, PayInfo payInfo)
			throws Exception {

		JSONObject tempJsonObject = null;
		// 微信App支付或者微信扫码支付，需要查找该用户的微信配置
		unionPayFullInfo = initUnionPay(unionPayFullInfo, payInfo);

		Map<String, String> queryMap = UnionPayUtil.queryOrder(
				unionPayFullInfo, payInfo);
		String return_code = queryMap.get("recode_code");
		if (return_code.equals("FAIL")) {
			// 业务处理失败，返回错误订单
			tempJsonObject = new JSONObject();
			tempJsonObject.put("order_num", payInfo.getMertradeNum());
			tempJsonObject.put("result_code", 0 + "");// 失败
			tempJsonObject.put("result_msg", queryMap.get("return_msg"));// 成功
			jsonArray.add(tempJsonObject);
		} else {
			String result_code = queryMap.get("result_code");
			if (result_code.equals("FAIL")) {
				// 业务处理失败，返回错误订单
				tempJsonObject = new JSONObject();
				tempJsonObject.put("order_num", payInfo.getMertradeNum());
				tempJsonObject.put("result_code", 0 + "");// 失败
				tempJsonObject.put("result_msg", queryMap.get("respMsg"));// 成功
				jsonArray.add(tempJsonObject);
			} else {

				
				
				payInfo.setPayResult('2');
				payInfoDao.updatePayResult(payInfo);
				
				tempJsonObject = new JSONObject();
				// tempJsonObject = new HashMap<String, String>();
				tempJsonObject.put("order_num", payInfo.getMertradeNum());
				tempJsonObject.put("result_code", 1 + "");// 成功
				
				// 1 微支付 2 支付成功
				// 3 支付失败 4 已关闭 5 已撤销(刷卡支付)
				// 6 用户支付中 7 转入退款
				tempJsonObject.put("payResult", SimpleUtil.getPayResultDe(payInfo.getPayResult()));
				jsonArray.add(tempJsonObject);
				// 保存对账信息
				BillHisInfo billHisInfo = billHisDao
						.queryBillByTradeNum(payInfo.getTradeId());
				if (billHisInfo == null)
					// 没有保存这个对账信息，新增对账信息
					saveBillHis(payInfo, '2');
			}
		}
	}

	/**
	 * 初始化银联支付配置
	 * @param unionPayFullInfo  银联支付配置
	 * @param payInfo   订单
	 * @return
	 * @throws Exception
	 */
	private UnionPayFullInfo initUnionPay(UnionPayFullInfo unionPayFullInfo, PayInfo payInfo) throws Exception{
		if(unionPayFullInfo ==null){
			//第一次加载微信配置
			unionPayFullInfo = unionPayFullDao.queryUnionPayFullBySiteId(payInfo.getWebSite().getId());
			if(unionPayFullInfo == null){	
				String mchID = SimpleUtil.b2CGateWayMap.get("mchID");
				String certPath = SimpleUtil.b2CGateWayMap.get("certPath");
				String mchKey = SimpleUtil.b2CGateWayMap.get("mchKey");
				unionPayFullInfo = new UnionPayFullInfo();
				unionPayFullInfo.setMchID(mchID);
				unionPayFullInfo.setMchKey(mchKey);
				unionPayFullInfo.setCertPath(certPath);
			}
		}
		return unionPayFullInfo;
	}

	/**
	 * 保存对账历史表
	 * @param payInfo  订单信息表
	 * @param billType  对账方式     2：主动查询
	 * @return
	 * @throws Exception
	 */
	private boolean saveBillHis(PayInfo payInfo,char billType) throws Exception{
		BillHisInfo billHisInfo = new BillHisInfo();
		
		billHisInfo.setPayId(payInfo.getId());
		billHisInfo.setPayType(payInfo.getPayType());
		billHisInfo.setSiteId(payInfo.getWebSite().getId());
		billHisInfo.setTradeNum(payInfo.getTradeNum());
		billHisInfo.setBillType(billType);// 
		billHisInfo.setBillResult(payInfo.getPayType().charAt(0));
		billHisInfo.setBillMsg(payInfo.getPaymsg());
		billHisInfo.setCreateTime(new Timestamp(new Date().getTime()));
		billHisInfo.setResultTime(payInfo.getResultTime());

		billHisDao.addBillHis(billHisInfo);
		
		return true;
	}
	/**
	 * B2C网关支付退款接口,同步不修改订单状态为退款成功状态，需要手动查询或者等待异步通知
	 * 
	 * @param siteToken  站点口令
	 * @param sign_value  加密后的订单id
	 * @return
	 */
	public Map<String, String> b2CGateWayPayBackTrans(String siteToken,
			String sign_value) throws Exception {
		Map<String, String> resultMap = new HashMap<String, String>();

		Map<String, Object> temptMap = invaldateKey(siteToken, sign_value);

		if (Integer.parseInt((String) resultMap.get("return_code")) == 0) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", (String) temptMap.get("return_msg"));
			return resultMap;
		}

		JSONObject jsonObject = null;
		try {
			// 将字符串转为Json
			jsonObject = JSONObject.parseObject(sign_value);
		} catch (Exception e) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg",
					SpringUtil.getI18nMsg("decode_val_error"));
			return resultMap;
		}
		String order_id = jsonObject.getString("order_id"); // 订单号
		PayInfo payInfo = payInfoDao.queryPayInfoByMertradeNum(order_id,
				siteToken);

		if (payInfo == null) {
			// 没有找到要撤销的订单
			resultMap.put("return_code", "0");
			resultMap
					.put("return_msg", SpringUtil.getI18nMsg("no_order_error"));
			return resultMap;
		}

		String payType = payInfo.getPayType();// 判断支付方式是否是银联支付
		if (!payType.trim().equals("000201")) {
			// 不是银联网关支付
			resultMap.put("return_code", "0");
			resultMap
					.put("return_msg", SpringUtil.getI18nMsg("order_PC_error"));
			return resultMap;
		}

		// 3、获取网站发起的支付方式是否已经接入
		Payment payment = paymentDao.queryPaymentBySiteIdAndPayType(payInfo
				.getWebSite().getId(), FengPayContraint.B2C_GATEWAY);
		if (payment == null) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_pay_type"));
			return resultMap;
		}

		UnionPayFullInfo unionPayFullInfo = null;
		// 判断用户的支付方式接入是否使用的营业执照
		if (payment.getIsFullInfo() == '1') {
			// 非营业执照接入，启动代理收款模式
			// ///加载本平台通过营业执照申请到的公钥私钥信息
			String mchID = SimpleUtil.b2CGateWayMap.get("mchID");
			String certPath = SimpleUtil.b2CGateWayMap.get("certPath");
			String mchKey = SimpleUtil.b2CGateWayMap.get("mchKey");

			unionPayFullInfo = new UnionPayFullInfo();
			unionPayFullInfo.setMchID(mchID);
			unionPayFullInfo.setMchKey(mchKey);
			unionPayFullInfo.setCertPath(certPath);
		} else
			unionPayFullInfo = unionPayFullDao
					.queryUnionPayFullBySiteId(payInfo.getWebSite().getId());

		resultMap = UnionPayUtil.B2CGateWayBackTrans(payInfo, unionPayFullInfo);

		String publicKey = payInfo.getWebSite().getPublicKey();
		resultMap.put("siteToken",
				RSAUtil.decryptByPublicKey(siteToken,publicKey));
		
		String return_code =resultMap.get("return_code"); 
		if(return_code.equals("1")){
			//更新订单的状态和保存订单的退货的流水号,等待异步通知退款结果
			payInfo.setPayResult('8');
			payInfo.setBackQueryId(resultMap.get("queryId"));
			payDao.updatePayResult(payInfo);
		}
		return resultMap;
	}
	/**
	 * 支付宝PC网站支付
	 * @param siteToken  站点口令
	 * @param sign_value
	 *            签名后的订单参数
	 * @return
	 */
	public Map<String, String> tradePagePayPay(String siteToken,
			String sign_value)  throws Exception {
		Map<String, Object> resultMap = invaldateKey(siteToken,sign_value);
		
		Map<String, String> map = new HashMap<String,String>();
		if(Integer.parseInt((String)resultMap.get("return_code"))  == 0){
			map.put("return_code", "0");
			map.put("return_msg", (String)resultMap.get("return_msg"));
			return map;
		}
		
		WebSite webSite = (WebSite) resultMap.get("webSite");
		
		String decodeData = null;
		try {
			// 获取接入站点的公钥
			String publicKey = webSite.getPublicKey();
			// 解密站点发送的订单
			decodeData = RSAUtil.decryptByPublicKey(sign_value,publicKey);
		} catch (Exception e) {
			throw new BaseException(e, false,
					SpringUtil.getI18nMsg("decode_val_error"));
		}
		JSONObject jsonObject = null;
		try {
			// 将字符串转为Json
			jsonObject = JSONObject.parseObject(decodeData);
		} catch (Exception e) {
			throw new BaseException(e, false,
					SpringUtil.getI18nMsg("decode_val_error"));
		}
		String order_id = jsonObject.getString("order_id"); // 订单号
		String total_pay = jsonObject.getString("total_pay");// 总金额
		String order_name = jsonObject.getString("order_name"); // 订单描述
		String payee = jsonObject.getString("payee"); // 收款人
		String order_detail = jsonObject.getString("order_detail"); // 订单详情
		// 2、校验签名数据，参数是否漏传
		if (isEmpty(order_id) || isEmpty(total_pay) || isEmpty(order_name)
				|| isEmpty(payee)) {
			map.put("return_code", "0");
			map.put("return_msg",
					SpringUtil.getI18nMsg("decode_val_error"));
			return map;
		}
		// 3、获取网站发起的支付方式是否已经接入
		Payment payment = paymentDao.queryPaymentBySiteIdAndPayType(
				webSite.getId(), FengPayContraint.ALIPAY_PCPAY);
		if (payment == null) {
			map.put("return_code", "0");
			map.put("return_msg", SpringUtil.getI18nMsg("no_pay_type"));
			return map;
		}

		AliPayFull aliPayFull = null;
		// 判断用户的支付方式接入是否使用的营业执照
		if (payment.getIsFullInfo() == '1') {
			// 非营业执照接入，启动代理收款模式
			// ///加载本平台通过营业执照申请到的公钥私钥信息
			String mchID = SimpleUtil.aliPayMap.get("mchID");
			String mchKey = SimpleUtil.aliPayMap.get("mchKey");
			String appID = SimpleUtil.aliPayMap.get("appID");
			aliPayFull = new AliPayFull();
			aliPayFull.setMchID(mchID);
			aliPayFull.setMchKey(mchKey);
			aliPayFull.setAppID(appID);
			
		} else{
			Integer siteId = webSite.getId();
			aliPayFull = aliPayFullDao.queryAliPayFullBySiteId(siteId);
		}

		PayInfo payInfo = payInfoDao.queryPayInfoByMertradeNum(order_id,
				siteToken);

		if (payInfo == null) {
			// 这个订单为第一次发起
			Date date = new Date();
			payInfo = new PayInfo();
			payInfo.setWebSite(webSite);
			payInfo.setTradeNum(SimpleUtil.getTradeNum());
			payInfo.setPayType(FengPayContraint.ALIPAY_PCPAY);
			payInfo.setMertradeNum(order_id);
			payInfo.setSubject(order_name);
			payInfo.setDetail(order_detail);
			payInfo.setTotal_fee(total_pay);
			payInfo.setSpbill_create_ip(SimpleUtil.getMyIp());
			payInfo.setTradeId(""); //支付宝支付没有此字段
			payInfo.setPayResult('1'); //支付状态为未支付
			payInfo.setChannelType("");//支付宝没有渠道类别
			payInfo.setCreateTime(new Timestamp(date.getTime()));
			payInfo.setNotifyResult(0);
			payInfoDao.addPayInfo(payInfo);
		} else {
			// 该订单已经存在于本系统中
			Timestamp currentTime = new Timestamp(new Date().getTime());
			Timestamp createTime = payInfo.getCreateTime();
			long timeResult = (currentTime.getTime() - createTime.getTime())
					/ (1000 * 60); // 两个timestamp得到毫秒数并相减，然后除以60000
			if (timeResult > 20) {
				// 超过20分钟没有支付
				map.put("return_code", "0");
				map.put("return_msg",
						SpringUtil.getI18nMsg("pay_time_pass"));
				return map;
			}
			if (payInfo.getPayResult() != '1') {
				// 订单已经结束
				map.put("return_code", "0");
				map.put("return_msg", SpringUtil.getI18nMsg("pay_over"));
				return map;
			}
			// 订单已经被提交过，且在支付时间范围内，而且订单状态为未支付状态，则更新订单信息（第三方系统中的用户可能更新了商品的数量、支付方式等）
			// payInfo.setWebSite(webSite);
			// payInfo.setTradeNum(SimpleUtil.getTradeNum(siteToken));
			payInfo.setPayType(FengPayContraint.ALIPAY_PCPAY);
			// payInfo.setMertradeNum(order_id);
			payInfo.setSubject(order_name);
			payInfo.setDetail(order_detail);
			payInfo.setTotal_fee(total_pay);
			// payInfo.setSpbill_create_ip(SimpleUtil.getMyIp());
			payInfo.setTradeId("");
			payInfo.setPayResult('1');
			payInfo.setChannelType("");
			
			payInfoDao.updatePayInfo(payInfo);
		}
		String formHtml = null;
		try {
			formHtml = AliPayUtil.initPayForm(aliPayFull, payInfo);
		} catch (Exception e) {
			throw new BaseException(e,false,SpringUtil.getI18nMsg("uniPay_order_error"));
		}
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("formHtml", formHtml);
			String signValue = RSAUtil.encryptByPublicKey(paramMap,
					webSite.getPublicKey());
			
			siteToken = RSAUtil.encryptByPublicKey(siteToken, webSite.getPublicKey());
			map.put("return_code", "1");
			map.put("siteToken", siteToken);
			map.put("order_form", signValue);
		} catch (Exception e) {
			throw new BaseException(e, false,
					SpringUtil.getI18nMsg("pay_result_encode_error"));
		}
		return map;
		
	}
	/**
	 * 查询订单信息
	 * @param out_trade_no  订单号
	 * @return
	 */
	public Map<String, String> queryOrderInfo(String out_trade_no) throws Exception  {
		PayInfo payInfo = payInfoDao.queryPayInfoByTradeNum(out_trade_no);
		Map<String, String> resultMap = new HashMap<String,String>();
		if(payInfo !=null){
			resultMap.put("return_code", "1");
			resultMap.put("tradeNum", payInfo.getMertradeNum());
			resultMap.put("order_title", payInfo.getSubject());
			
			resultMap.put("order_desc", payInfo.getDetail());
			
			Integer total_fee = Integer.parseInt(payInfo.getTotal_fee());
			resultMap.put("total_fee",""+(total_fee/100+total_fee%100*0.01));
			String payType = payInfo.getPayType();
			payType = SimpleUtil.getChinesePayType(payType);
			resultMap.put("payType",payType);
		}else {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_order_error"));
		}
		return resultMap;
		
	}
	/**
	 * 查询支付宝支付订单状态
	 * @param siteToken  站点口令
	 * @param sign_value
	 *            签名后的订单号列表
	 * @return
	 */

	@SuppressWarnings("static-access")
	public Map<String, String> queryAliPayOrder(String siteToken,
			String sign_value) throws Exception{

		Map<String, String> resultMap = new HashMap<String, String>();


		Map<String, Object> tempMap = invaldateKey(siteToken, sign_value);

		if (Integer.parseInt((String) tempMap.get("return_code")) == 0) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", (String) tempMap.get("return_msg"));
			return resultMap;
		}
		WebSite webSite = (WebSite) tempMap.get("webSite");
		
		String decodeData = null;
		String publicKey  =null;
		try {
			//获取接入站点的公钥
			publicKey = webSite.getPublicKey();
			//解密站点发送的订单
			decodeData = RSAUtil.decryptByPublicKey(sign_value,publicKey);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException(e,false,SpringUtil.getI18nMsg("decode_val_error"));
		}
		JSONObject jsonObject = null;
		try {
			//将字符串转为Json
			jsonObject = JSONObject.parseObject(decodeData);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException(e,false,SpringUtil.getI18nMsg("decode_val_error"));
		}
		JSONArray  orderIds  = null;
		try {
			 orderIds = jsonObject.getJSONArray("order_ids");
		} catch (Exception e) {
			logger.error("return_msg\t:"+SpringUtil.getI18nMsg("out_orderIds_error"));
			e.printStackTrace();
			throw new BaseException(e,false,SpringUtil.getI18nMsg("out_orderIds_error"));
		}
		JSONArray jsonArray = new JSONArray();
		PayInfo payInfo =null;
	
		JSONObject tempJsonObject = null;
		for (int i = 0; i < orderIds.size(); i++) {
			String mertradeNum = orderIds.getString(i);
			payInfo = payInfoDao.queryPayInfoByMertradeNum(mertradeNum, siteToken);
			if(payInfo == null){
				//没有查询到订单
				tempJsonObject = new JSONObject();
				tempJsonObject.put("order_num", mertradeNum);
				tempJsonObject.put("result_code", 0+"");//错误
				tempJsonObject.put("result_msg", SpringUtil.getI18nMsg("no_order_error"));
				jsonArray.add(tempJsonObject);
				continue;
			}
			String payType = payInfo.getPayType();//支付方式
			//支付方式不是支付宝支付
			if(!payType.equals(FengPayContraint.ALIPAY_PCPAY)){
				tempJsonObject = new JSONObject();
				tempJsonObject.put("order_num", payInfo.getMertradeNum());
				tempJsonObject.put("result_code", 0+"");//失败
				tempJsonObject.put("result_msg", SpringUtil.getI18nMsg("not_unionPay_order"));//
				jsonArray.add(tempJsonObject);
				continue;
			}
			
			if(payInfo.getPayResult()== '2' || payInfo.getPayResult()== '3' || payInfo.getPayResult() == '4'){
				//本平台中此订单的支付状态已经改变了，不再查询
				tempJsonObject = new JSONObject();
//				tempMap = new HashMap<String, String>();
				tempJsonObject.put("order_num", payInfo.getMertradeNum());
				tempJsonObject.put("result_code", 1+"");//成功
				tempJsonObject.put("payResult", SimpleUtil.getPayResultDe(payInfo.getPayResult()));//成功
				jsonArray.add(tempJsonObject);
				continue;
			}else if( payInfo.getPayResult() == '5'){
				//本平台中此订单的已经退款成功，不再查询
				tempJsonObject = new JSONObject();
//				tempMap = new HashMap<String, String>();
				tempJsonObject.put("order_num", payInfo.getMertradeNum());
				tempJsonObject.put("result_code", 1+"");//成功
				tempJsonObject.put("payResult", SimpleUtil.getPayResultDe(payInfo.getPayResult()));////超时关闭，或支付完成后全额退款 
				jsonArray.add(tempJsonObject);
				continue;
			}
			AliPayFull aliPayFull = null;
			aliPayFull = initAliPay(aliPayFull, payInfo);
			//银联、支付宝撤销订单可同用同一个撤销订单实体类
			if(payInfo.getPayResult()== '8' ){
				//本平台中此订单为退款订单，且在退款中，需要查找银联支付插销订单信息表，然后根据订单信息表中的信息去查询撤销结果
				UnionPayBackInfo unionPayBackInfo = unionPayBackInfoDao.queryPayInfoByMertradeNum(mertradeNum, siteToken);
				if(unionPayBackInfo == null){
					tempJsonObject = new JSONObject();
					tempJsonObject.put("order_num", payInfo.getMertradeNum());
					tempJsonObject.put("result_code", 0+"");//失败
					tempJsonObject.put("result_msg", SpringUtil.getI18nMsg("unionPay_back_noOrder"));//
					jsonArray.add(tempJsonObject);
					continue;
				}
				//支付宝查询交易状态，不管是退款，还是支付结果，使用的均是同一个订单号
				Map<String, String> tempResultMap = AliPayUtil.queryRefundOrder(aliPayFull, payInfo);
				
				String result_code = tempResultMap.get("return_code");
				if(result_code.trim().equals("1")){
					//修改订单/撤销订单状态为已退款（撤销）
					payInfo.setPayResult('5'); //已撤销
					payInfoDao.updatePayInfo(payInfo);
					
					unionPayBackInfo.setPayResult('1');
					unionPayBackInfo.setPaymsg("");
					unionPayBackInfo.setQueryId(tempResultMap.get("trade_no")); //支付宝交易号
					
					unionPayBackInfoDao.updatePayBackInfo(unionPayBackInfo);
					
					//返回订单结果
					tempJsonObject = new JSONObject();
					tempJsonObject.put("order_num", payInfo.getMertradeNum());
					tempJsonObject.put("result_code", 1+"");//成功
					tempJsonObject.put("payResult", SimpleUtil.getPayResultDe(payInfo.getPayResult()));//超时关闭，或支付完成后全额退款 
					jsonArray.add(tempJsonObject);
				}else{
					//检查状态失败，直接返回返回
					tempJsonObject = new JSONObject();
					tempJsonObject.put("order_num", payInfo.getMertradeNum());
					tempJsonObject.put("result_code", 0+"");//失败
					tempJsonObject.put("result_msg", SpringUtil.getI18nMsg("order_result_no"));//
					jsonArray.add(tempJsonObject);
				}
				
			}else if(payInfo.getPayResult()== '1' ){
				//正在支付中,需要查询订单支付状态，然后修改订单表，最后返回给用户
				Map<String, String> tempResultMap = AliPayUtil.queryOrder(aliPayFull, payInfo);
				
				String result_code = tempResultMap.get("return_code");
				if(result_code.trim().equals("1")){
//					String trade_no = tempResultMap.get("trade_no");//支付宝交易号
					String jsonStr = tempResultMap.get("responseBody");
					JSONObject responseJson = jsonObject.parseObject(jsonStr);
					JSONObject content = responseJson.getJSONObject("alipay_trade_query_response");
//					String sign = responseJson.getString("sign");
//					boolean result = AliPayUtil.vertifyDate(content.toString(), sign, aliPayFull);
					String code = content.getString("code"); //10000
					String out_trade_no = content.getString("out_trade_no"); //商户订单号
					String total_amount = content.getString("total_amount"); //订单总金额
//					String trade_no = content.getString("trade_no"); //支付宝订单号
					String trade_status = content.getString("trade_status"); //交易状态 TRADE_SUCCESS
					total_amount = AliPayUtil.changeY2F(total_amount);
					if(code !=null && code.equals("10000") && total_amount.equals(payInfo.getTotal_fee()) ){
						if(trade_status !=null && (trade_status.equals("TRADE_SUCCESS")||trade_status.equals("TRADE_FINISHED"))){
							//交易成功
							payInfo.setPayResult('2'); //支付成功
							payInfo.setPaymsg("成功");
						}else if(trade_status !=null && trade_status.equals("WAIT_BUYER_PAY")){
							//等待支付
//							payInfo.setPayResult('1');
//							payInfo.setPaymsg("等待支付");
							tempJsonObject = new JSONObject();
							tempJsonObject.put("order_num", payInfo.getMertradeNum());
							tempJsonObject.put("result_code", "1");//成功
							tempJsonObject.put("payResult", SimpleUtil.getPayResultDe('1'));
							jsonArray.add(tempJsonObject);
							continue;
						}else if(trade_status !=null && trade_status.equals("TRADE_CLOSED")){
							//交易关闭
							payInfo.setPayResult('4');
							payInfo.setPaymsg("超时关闭，或支付完成后全额退款");
						}else{
							logger.error("其他状态，请检查订单号:"+out_trade_no+",订单状态为:"+trade_status);
							tempJsonObject = new JSONObject();
							tempJsonObject.put("order_num", payInfo.getMertradeNum());
							tempJsonObject.put("result_code", "0");//失败
							tempJsonObject.put("result_msg", SpringUtil.getI18nMsg("pay_resp_code_error"));//
							jsonArray.add(tempJsonObject);
							continue;
						}
						payInfo.setQueryId(tempResultMap.get("trade_no")); //支付宝交易号
						payInfoDao.updatePayResult(payInfo);
						// 保存对账信息
//						String out_trade_no = (String)tempResultMap.get("orderId"); //内部交易订单号
						BillHisInfo billHisInfo = billHisDao
								.queryBillByTradeNum(out_trade_no);
						if (billHisInfo == null) {
							billHisInfo =  new BillHisInfo();
							billHisInfo.setPayId(payInfo.getId());
							billHisInfo.setPayType(payInfo.getPayType());
							billHisInfo.setSiteId(payInfo.getWebSite().getId());
							billHisInfo.setTradeNum(out_trade_no);
							billHisInfo.setBillType('1');//主动查询
							billHisInfo.setBillResult(tempResultMap.get("return_code").equals(
									"1") ? '2' : '3');
							billHisInfo
									.setBillMsg(tempResultMap.get("return_code").equals("1") ? tempResultMap
											.get("return_code")
											+ "-------"
											+ tempResultMap.get("return_msg") : "");
							billHisInfo.setCreateTime(new Timestamp(new Date().getTime()));
							SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
							Timestamp send_pay_date = new Timestamp(format.parse((String)tempResultMap.get("send_pay_date")).getTime());
							
							billHisInfo.setResultTime(send_pay_date);  //本次交易打款给卖家的时间
		
							billHisDao.addBillHis(billHisInfo);
						}
					}else{
						//失败
						tempJsonObject = new JSONObject();
						tempJsonObject.put("order_num", payInfo.getMertradeNum());
						tempJsonObject.put("result_code", "0");//失败
						tempJsonObject.put("result_msg", SpringUtil.getI18nMsg("order_result_no"));//
						jsonArray.add(tempJsonObject);
						continue;
					}
				}else{
					//查询支付状态失败，需要再次查询
					tempJsonObject = new JSONObject();
					tempJsonObject.put("order_num", payInfo.getMertradeNum());
					tempJsonObject.put("result_code", "0");//失败
					tempJsonObject.put("result_msg", SpringUtil.getI18nMsg("order_result_no"));//
					jsonArray.add(tempJsonObject);
				}
			}
		}
		resultMap.put("return_code", "1");//成功
		String sign_val = RSAUtil.encryptByPublicKey(jsonArray.toJSONString(), webSite.getPublicKey());
		resultMap.put("respContent", sign_val);
		return resultMap;
	}
	
	
	/**
	 * 初始化支付宝支付配置
	 * @param aliPayFull  支付宝支付配置
	 * @param payInfo   订单
	 * @return
	 * @throws Exception
	 */
	private AliPayFull initAliPay(AliPayFull aliPayFull, PayInfo payInfo) {
		if(aliPayFull ==null){
			//第一次加载微信配置
			aliPayFull = aliPayFullDao.queryAliPayFullBySiteId(payInfo.getWebSite().getId());
			if(aliPayFull == null){	
				String mchID = SimpleUtil.aliPayMap.get("mchID");
				String mchKey = SimpleUtil.aliPayMap.get("mchKey");
				String appID = SimpleUtil.aliPayMap.get("appID");
				aliPayFull = new AliPayFull();
				aliPayFull.setMchID(mchID);
				aliPayFull.setMchKey(mchKey);
				aliPayFull.setAppID(appID);
			}
		}
		return aliPayFull;
	}

	
	/**
	 * 支付宝交易退款
	 * @param siteToken  站点口令
	 * @param sign_value 要退款的订单号
	 * @return
	 */
	public Map<String, String> refundOrder(String siteToken, String sign_value) throws Exception{
		
		Map<String, String> resultMap = new HashMap<String, String>();

		Map<String, Object> tempMap = invaldateKey(siteToken, sign_value);

		if (Integer.parseInt((String) tempMap.get("return_code")) == 0) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", (String) tempMap.get("return_msg"));
			return resultMap;
		}
		WebSite webSite = (WebSite) tempMap.get("webSite");
		
		String decodeData = null;
		String publicKey  =null;
		try {
			//获取接入站点的公钥
			publicKey = webSite.getPublicKey();
			//解密站点发送的订单
			decodeData = RSAUtil.decryptByPublicKey(sign_value,publicKey);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException(e,false,SpringUtil.getI18nMsg("decode_val_error"));
		}
		JSONObject jsonObject = null;
		try {
			// 将字符串转为Json
			jsonObject = JSONObject.parseObject(decodeData);
		} catch (Exception e) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg",
					SpringUtil.getI18nMsg("decode_val_error"));
			return resultMap;
		}
		String order_id = jsonObject.getString("order_id"); // 订单号
		PayInfo payInfo = payInfoDao.queryPayInfoByMertradeNum(order_id,
				siteToken);

		if (payInfo == null) {
			// 没有找到要撤销的订单
			resultMap.put("return_code", "0");
			resultMap
					.put("return_msg", SpringUtil.getI18nMsg("no_order_error"));
			return resultMap;
		}

		String payType = payInfo.getPayType();// 判断支付方式是否是支付宝支付
		if (!payType.trim().equals(FengPayContraint.ALIPAY_PCPAY)) {
			// 不是支付宝支付
			resultMap.put("return_code", "0");
			resultMap
					.put("return_msg", SpringUtil.getI18nMsg("not_aliPay_order"));
			return resultMap;
		}

		// 3、获取网站发起的支付方式是否已经接入
		Payment payment = paymentDao.queryPaymentBySiteIdAndPayType(payInfo
				.getWebSite().getId(), FengPayContraint.ALIPAY_PCPAY);
		if (payment == null) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_pay_type"));
			return resultMap;
		}

		AliPayFull aliPayFull = null;
		// 判断用户的支付方式接入是否使用的营业执照
		if (payment.getIsFullInfo() == '1') {
			// 非营业执照接入，启动代理收款模式
			// ///加载本平台通过营业执照申请到的公钥私钥信息
			String mchID = SimpleUtil.aliPayMap.get("mchID");
			String mchKey = SimpleUtil.aliPayMap.get("mchKey");
			String appID = SimpleUtil.aliPayMap.get("appID");
			aliPayFull = new AliPayFull();
			aliPayFull.setMchID(mchID);
			aliPayFull.setMchKey(mchKey);
			aliPayFull.setAppID(appID);
		} else
			aliPayFull = aliPayFullDao.queryAliPayFullBySiteId(payInfo.getWebSite().getId());
		
		
		Map<String, String> refundMap = AliPayUtil.refundOrder(aliPayFull, payInfo);
		String return_code =refundMap.get("return_code"); 
		if(return_code.equals("1")){
			String responseBody = refundMap.get("responseBody");
			//body 样例 {"alipay_trade_refund_response":{"code":"10000","msg":"Success","buyer_logon_id":"stq***@sandbox.com","buyer_user_id":"2088102170460027","fund_change":"Y","gmt_refund_pay":"2017-12-15 15:52:40","open_id":"20880056007627551754882190217902","out_trade_no":"PM20171215145939","refund_fee":"1.32","send_back_fee":"0.00","trade_no":"2017121521001004020200257886"},"sign":"vgEGNv1SmxlqhRv3WiCUYAnyYfgoymYVqVXK4X+/ATxuV8Hg16xR9PxdatytCIw2+mw169Zu2QeAlBFN6O/g633uoiND2fUtLDqlf6KzRLR4DqkRaeMFgSpztpxritmT5pLq81mPbePaELBP99hufoPUj9pIwc/TNxb9ft701/zw2a1dQl+bzpSO9HJsWxJjDVY0tEJjp9DVHV3jUXcGSjv7lCpaFdzehBzF6kl7t2J9D8z/FJa9bu27YTw8svnb2zCSbRDCD3eDbXNyp0Aai6y74M0agK9jRolpOhraxHu8sJA29NvXqhSX+v9PbuykdNZqYKQx7GBPMjOfGiyVig=="}
			JSONObject responseBodyJson = JSONObject.parseObject(responseBody);
			JSONObject contentJson = responseBodyJson.getJSONObject("alipay_trade_refund_response");
			
			String code =contentJson.getString("code");
			//2017-12-15 15:52:40
			String gmt_refund_pay = contentJson.getString("gmt_refund_pay");  //退款时间
			String out_trade_no = contentJson.getString("out_trade_no");  //商家订单号 ，注意，本项目支付宝退款时的订单号和支付订单号相同
			String refund_fee = contentJson.getString("refund_fee");  //退款金额
			String trade_no = contentJson.getString("trade_no");  //支付宝退款交易号
			if(code != null && code.equals("10000")){
				if(out_trade_no !=null && out_trade_no.equals(payInfo.getTradeNum()) && refund_fee!=null && AliPayUtil.changeY2F(refund_fee).equals(payInfo.getTotal_fee())){
					//退款成功
					//更新订单的状态和保存订单的退货的流水号,等待异步通知退款结果
					payInfo.setPayResult('5');
					payInfo.setBackQueryId(trade_no); //支付宝交易号
					payDao.updatePayResult(payInfo);
					
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Timestamp date = new Timestamp(format.parse(gmt_refund_pay).getTime());
					
					//初始化退款订单，所有的退款订单均可用 UnionPayBackInfo
					UnionPayBackInfo payBackInfo = unionPayBackInfoDao.queryPayInfoByMertradeNum(order_id, siteToken);
					if(payBackInfo == null){
						payBackInfo =initOrderBackInfo(payInfo);
						payBackInfo.setQueryId(trade_no);
						payBackInfo.setResultTime(date);
						payBackInfo.setBackCreateTime(new Timestamp(new Date().getTime()));
						payBackInfo.setBackQueryId(out_trade_no);
						unionPayBackInfoDao.addUnionPayBackInfo(payBackInfo);
					}else{
						//payResult= #{payResult},paymsg = #{paymsg},queryId = #{queryId}
						payBackInfo.setPayResult('1');  //撤销成功
						payBackInfo.setQueryId(trade_no);
						payBackInfo.setBackCreateTime(new Timestamp(new Date().getTime()));
						payBackInfo.setBackQueryId(out_trade_no);
						payBackInfo.setResultTime(date);
						unionPayBackInfoDao.updatePayBackInfo(payBackInfo);
					}
					resultMap.put("return_code", "1");
				}else{
					resultMap.put("return_code", "0");
					resultMap.put("return_msg", SpringUtil.getI18nMsg("decode_resp_error"));
				}
			}else{
				resultMap.put("return_code", "0");
				resultMap.put("return_msg", SpringUtil.getI18nMsg("aliPay_refund_resp_error:---"+code));
			}
		}else{
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("aliPay_refund_error"));
		}
		resultMap.put("siteToken",
				RSAUtil.encryptByPublicKey(siteToken,publicKey));
		
		return resultMap;
	}
	/**
	 * 处理支付宝支付结果同步通知
	 * 
	 * 1、获取orderid 查询商户的信息，获取值支付宝公钥
	 * 2、支付宝验签
	 * 3、验证订单是否已经处理过（订单状态），处理过则不进行任何处理
	 * 4、校验必要参数是否和系统中的订单参数相同
	 * 
	 * @param paramMap 通知的参数集合
	 * @return
	 */
	public Map<String, String> aliPaySyncRes(Map<String, String> paramMap) throws Exception {
		logger.info("----------------- aliPaySyncRes 入参:"+paramMap);
		Map<String, String> resultMap = new HashMap<String,String>();
		if(paramMap == null || paramMap.isEmpty()){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("pay_resp_code_error"));
			return resultMap;
		}
		
		String out_trade_no = paramMap.get("out_trade_no");
		PayInfo payInfo = payInfoDao.queryPayInfoByTradeNum(out_trade_no);
		if(payInfo ==null){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_order_error"));
			return resultMap;
		}
		
		// 获取网站发起的支付方式是否已经接入
		Payment payment = paymentDao.queryPaymentBySiteIdAndPayType(
				payInfo.getWebSite().getId(), payInfo.getPayType());
		if (payment == null) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_pay_type"));
			return resultMap;
		}
		AliPayFull aliPayFull = null;
		// 判断用户的支付方式接入是否使用的营业执照
		if (payment.getIsFullInfo() == '1') {
			// 非营业执照接入，启动代理收款模式
			// ///加载本平台通过营业执照申请到的公钥私钥信息
			String mchID = SimpleUtil.aliPayMap.get("mchID");
			String mchKey = SimpleUtil.aliPayMap.get("mchKey");
			String appID = SimpleUtil.aliPayMap.get("appID");
			aliPayFull = new AliPayFull();
			aliPayFull.setMchID(mchID);
			aliPayFull.setMchKey(mchKey);
			aliPayFull.setAppID(appID);
		} else{
			Integer siteId = payInfo.getWebSite().getId();
			aliPayFull = aliPayFullDao.queryAliPayFullBySiteId(siteId);
		}
		
		Map<String, String> vertifyMap = AliPayUtil.vertifyDate(paramMap, aliPayFull.getPublicKey());
		String return_code = vertifyMap.get("return_code");
		if(return_code == "0"){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", vertifyMap.get("return_msg"));
			return resultMap;
		}
		
		String totalFee = paramMap.get("total_amount");

		totalFee = AliPayUtil.changeY2F(totalFee);
		if(totalFee.equals(payInfo.getTotal_fee())){
			payInfo.setQueryId(paramMap.get("trade_no")); //支付宝交易号
			payInfo.setPayResult('2'); //支付成功
			payInfo.setPaymsg("成功");
			
			resultMap.put("return_code", "1");
			
			resultMap.put("tradeNum", payInfo.getMertradeNum());
			resultMap.put("order_title", payInfo.getSubject());
			
			resultMap.put("order_desc", payInfo.getDetail());
			
			resultMap.put("total_fee",""+AliPayUtil.changeF2Y(totalFee));
			String payType = payInfo.getPayType();
			payType = SimpleUtil.getChinesePayType(payType);
			resultMap.put("payType",payType);
			return resultMap;
		}else{
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("order_result_no"));
			return resultMap;
		}
	}
	/*public Map<String, String> aliPaySyncRes(Map<String, String> paramMap) throws Exception {
		logger.info("----------------- aliPaySyncRes 入参:"+paramMap);
		Map<String, String> resultMap = new HashMap<String,String>();
		if(paramMap == null || paramMap.isEmpty()){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("pay_resp_code_error"));
			return resultMap;
		}
		
		String out_trade_no = paramMap.get("out_trade_no");
		PayInfo payInfo = payInfoDao.queryPayInfoByTradeNum(out_trade_no);
		if(payInfo ==null){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_order_error"));
			return resultMap;
		}
		
		// 获取网站发起的支付方式是否已经接入
		Payment payment = paymentDao.queryPaymentBySiteIdAndPayType(
				payInfo.getWebSite().getId(), payInfo.getPayType());
		if (payment == null) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_pay_type"));
			return resultMap;
		}
		AliPayFull aliPayFull = null;
		// 判断用户的支付方式接入是否使用的营业执照
		if (payment.getIsFullInfo() == '1') {
			// 非营业执照接入，启动代理收款模式
			// ///加载本平台通过营业执照申请到的公钥私钥信息
			String mchID = SimpleUtil.aliPayMap.get("mchID");
			String mchKey = SimpleUtil.aliPayMap.get("mchKey");
			String appID = SimpleUtil.aliPayMap.get("appID");
			aliPayFull = new AliPayFull();
			aliPayFull.setMchID(mchID);
			aliPayFull.setMchKey(mchKey);
			aliPayFull.setAppID(appID);
		} else{
			Integer siteId = payInfo.getWebSite().getId();
			aliPayFull = aliPayFullDao.queryAliPayFullBySiteId(siteId);
		}
		
		Map<String, String> vertifyMap = AliPayUtil.vertifyDate(paramMap, aliPayFull.getPublicKey());
		String return_code = vertifyMap.get("return_code");
		if(return_code == "0"){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", vertifyMap.get("return_msg"));
			return resultMap;
		}
		
		String totalFee = paramMap.get("total_amount");

		totalFee = AliPayUtil.changeY2F(totalFee);
		if(totalFee.equals(payInfo.getTotal_fee())){
			payInfo.setQueryId(paramMap.get("trade_no")); //支付宝交易号
			payInfo.setPayResult('2'); //支付成功
			payInfo.setPaymsg("成功");
			payInfoDao.updatePayResult(payInfo);
			
			//保存账单信息
			BillHisInfo billHisInfo = billHisDao
					.queryBillByTradeNum(out_trade_no);
			if (billHisInfo == null) {
				billHisInfo =  new BillHisInfo();
				billHisInfo.setPayId(payInfo.getId());
				billHisInfo.setPayType(payInfo.getPayType());
				billHisInfo.setSiteId(payInfo.getWebSite().getId());
				billHisInfo.setTradeNum(out_trade_no);
				billHisInfo.setBillType('4');//同步通知
				billHisInfo.setBillResult('2'); //支付成功
				billHisInfo
						.setBillMsg("同步通知支付成功");
				billHisInfo.setCreateTime(new Timestamp(new Date().getTime()));
				SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
				Timestamp send_pay_date = new Timestamp(format.parse((String)paramMap.get("send_pay_date")).getTime());
				
				billHisInfo.setResultTime(send_pay_date);  //本次交易打款给卖家的时间
				billHisDao.addBillHis(billHisInfo);
			}
			
			
			//异步通知，需要返回给第三方系统通知结果
			
			resultMap.put("return_code", "1");
			
			resultMap.put("tradeNum", payInfo.getMertradeNum());
			resultMap.put("order_title", payInfo.getSubject());
			
			resultMap.put("order_desc", payInfo.getDetail());
			
			resultMap.put("total_fee",""+AliPayUtil.changeF2Y(totalFee));
			String payType = payInfo.getPayType();
			payType = SimpleUtil.getChinesePayType(payType);
			resultMap.put("payType",payType);
			return resultMap;
		}else{
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("order_result_no"));
			return resultMap;
		}
	}*/
	/**
	 * 处理支付宝支付结果异步通知
	 * 
	 * 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	 * 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	 * 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据
	 * 		的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email），
	 * 4、验证app_id是否为该商户本身。
	 * 上述1、2、3、4有任何一个验证不通过，则表明本次通知是异常通知，务必忽略。
	 * 在上述验证通过后商户必须根据支付宝不同类型的业务通知，正确的进行不同的业务处理，
	 * 并且过滤重复的通知结果数据。
	 * 在支付宝的业务通知中，只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时，
	 * 支付宝才会认定为买家付款成功。
	 * @param paramMap 通知的参数集合
	 * @return
	 */
	public Map<String, String> aliPayAsyncRes(Map<String, String> paramMap) throws Exception{

		logger.info("----------------- aliPayAsyncRes 入参:"+paramMap);
		Map<String, String> resultMap = new HashMap<String,String>();
		if(paramMap == null || paramMap.isEmpty()){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("pay_resp_code_error"));
			return resultMap;
		}
		
		String out_trade_no = paramMap.get("out_trade_no");
		PayInfo payInfo = payInfoDao.queryPayInfoByTradeNum(out_trade_no);
		if(payInfo ==null){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_order_error"));
			return resultMap;
		}
		String total_amount = paramMap.get("total_amount");
		String total_fee = payInfo.getTotal_fee();
		
		if(!total_fee.equals(AliPayUtil.changeY2F(total_amount))){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("check_order_total_fee_error"));
			return resultMap;
		}
		// 获取网站发起的支付方式是否已经接入
		Payment payment = paymentDao.queryPaymentBySiteIdAndPayType(
				payInfo.getWebSite().getId(), payInfo.getPayType());
		if (payment == null) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_pay_type"));
			return resultMap;
		}
		AliPayFull aliPayFull = null;
		// 判断用户的支付方式接入是否使用的营业执照
		if (payment.getIsFullInfo() == '1') {
			// 非营业执照接入，启动代理收款模式
			// ///加载本平台通过营业执照申请到的公钥私钥信息
			String mchID = SimpleUtil.aliPayMap.get("mchID");
			String mchKey = SimpleUtil.aliPayMap.get("mchKey");
			String appID = SimpleUtil.aliPayMap.get("appID");
			aliPayFull = new AliPayFull();
			aliPayFull.setMchID(mchID);
			aliPayFull.setMchKey(mchKey);
			aliPayFull.setAppID(appID);
		} else{
			Integer siteId = payInfo.getWebSite().getId();
			aliPayFull = aliPayFullDao.queryAliPayFullBySiteId(siteId);
		}
		
		String seller_id = paramMap.get("seller_id");
		
		if(!seller_id.equals(aliPayFull.getMchID())){
			//卖家ID跟数据库中的商家ID不相同
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("check_order_mch_id_error"));
			return resultMap;
		}
		String app_id = paramMap.get("app_id");
		if(!app_id.equals(aliPayFull.getAppID())){
			//卖家应用ID跟数据库中的应用ID不相同
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("check_order_app_id_error"));
			return resultMap;
		}
		
		Map<String, String> vertifyMap = AliPayUtil.vertifyDate(paramMap, aliPayFull.getPublicKey());
		String return_code = vertifyMap.get("return_code");
		if(return_code == "0"){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", vertifyMap.get("return_msg"));
			return resultMap;
		}
		
		char payResult = payInfo.getPayResult();
		if(SimpleUtil.orderIsSucces(payResult)){
			//订单状态已经修改、无需再次修改
			resultMap.put("return_code", "1");
			return resultMap;
		}
		
		/**
		 * 在支付宝的业务通知中，只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时，
		 * 支付宝才会认定为买家付款成功。
		 */
		char tPayResult ;
		String msg = "";
		String trade_status = paramMap.get("trade_status");
		if(trade_status.equals("TRADE_SUCCESS") || trade_status.equals("TRADE_FINISHED")){
			//TRADE_SUCCESS 交易支付成功  TRADE_FINISHED 交易结束，不可退款    
			tPayResult = '2'; //支付成功
			msg = "成功";
		}else if(trade_status.equals("TRADE_CLOSED")){
			//未付款交易超时关闭，或支付完成后全额退款
			tPayResult = '4'; //未付款交易超时关闭，或支付完成后全额退款
			msg = "关闭或全额退款";
		}else{
			logger.error("----orderid:"+payInfo.getTradeNum()+",查询到的订单状态:"+trade_status+"未知");
			tPayResult = '1';
		}
		payInfo.setPayResult(tPayResult);
		
		//通知第三方系统，返回给支付宝处理结果
		Integer sendResultInteger = HttpsUtil.sendMsgToClient(payInfo.getMertradeNum(), payInfo.getTotal_fee(), payInfo.getPayResult(), payInfo.getWebSite().getSiteToken(), payInfo.getWebSite().getPublicKey(), payInfo.getWebSite().getSiteUrl());
		
		payInfo.setNotifyResult(sendResultInteger);
		payInfo.setPaymsg(msg);
		payInfo.setQueryId(paramMap.get("trade_no")); //支付宝交易号
		payInfoDao.updatePayResult(payInfo);
		//保存账单信息
		BillHisInfo billHisInfo = billHisDao
				.queryBillByTradeNum(out_trade_no);
		if (billHisInfo == null) {
			billHisInfo =  new BillHisInfo();
			billHisInfo.setPayId(payInfo.getId());
			billHisInfo.setPayType(payInfo.getPayType());
			billHisInfo.setSiteId(payInfo.getWebSite().getId());
			billHisInfo.setTradeNum(out_trade_no);
			billHisInfo.setBillType('2');//异步通知
			billHisInfo.setBillResult(tPayResult); //支付结果
			billHisInfo
					.setBillMsg("异步通知结果");
			billHisInfo.setCreateTime(new Timestamp(new Date().getTime()));
			String gmt_payment  = paramMap.get("gmt_payment");
			
			SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
			Timestamp send_pay_date = new Timestamp(format.parse(gmt_payment).getTime());
			
			billHisInfo.setResultTime(send_pay_date);  //本次交易打款给卖家的时间
			billHisDao.addBillHis(billHisInfo);
		}else{
			//更新账单表
			String gmt_payment  = paramMap.get("gmt_payment");
			
			SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
			Timestamp send_pay_date = new Timestamp(format.parse(gmt_payment).getTime());
			
			billHisInfo.setResultTime(send_pay_date);  //本次交易打款给卖家的时间
			billHisInfo.setBillResult(tPayResult); //支付结果
			billHisInfo
					.setBillMsg("异步通知结果");
			
			billHisDao.updateBillHis(billHisInfo);
		}
		if(sendResultInteger == 1){
			// 通知过程中出现异常，记录通知过程，等待下次通知
			BillHisErrorInfo billHisErrorInfo = null;
			
			billHisErrorInfo = billHisErrorDao.queryBillHisErrorInfo(payInfo.getTradeNum(),payInfo.getWebSite().getId());
			if(billHisErrorInfo == null){
				//保存
				billHisErrorInfo = new BillHisErrorInfo();

				billHisErrorInfo.setPayId(payInfo.getId());
				billHisErrorInfo.setPayType(payInfo.getPayType());
				billHisErrorInfo.setSiteId(payInfo.getWebSite().getId());
				billHisErrorInfo.setTradeNum(out_trade_no);
				billHisErrorInfo.setBillType('2');// 异步通知
				billHisErrorInfo.setBillResult(tPayResult);
				billHisErrorInfo.setBillMsg("通知第三方系统出错!");
				billHisErrorInfo.setCreateTime(new Timestamp(new Date()
						.getTime()));
				String gmt_payment  = paramMap.get("gmt_payment");
				
				SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
				Timestamp send_pay_date = new Timestamp(format.parse(gmt_payment).getTime());
				
				billHisErrorInfo.setResultTime(send_pay_date);
				billHisErrorInfo.setErrorMsg("通知第三方系统出错!");
				billHisErrorInfo.setNotifyNum(1);
				billHisErrorDao.addBillHis(billHisErrorInfo);
			}else {
				//更新
				billHisErrorInfo.setNotifyNum(billHisErrorInfo.getNotifyNum()+1);;
				billHisErrorInfo.setBillMsg("通知第三方系统出错!");
				billHisErrorInfo.setErrorMsg("通知第三方系统出错!");
				billHisErrorInfo.setBillType('2');// 异步通知
				billHisErrorInfo.setBillResult(tPayResult);
				billHisErrorDao.updateBillHis(billHisErrorInfo);
			}
			
		}
		
		resultMap.put("return_code", "1");
		return resultMap;
	}

	@Override
	public Map<String, String> downloadBillFile(String siteToken,
			String sign_value)  throws Exception {
		Map<String, String> resultMap = new HashMap<String, String>();

		Map<String, Object> tempMap = invaldateKey(siteToken, sign_value);

		if (Integer.parseInt((String) tempMap.get("return_code")) == 0) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", (String) tempMap.get("return_msg"));
			return resultMap;
		}
		WebSite webSite = (WebSite) tempMap.get("webSite");
		
		String decodeData = null;
		String publicKey  =null;
		try {
			//获取接入站点的公钥
			publicKey = webSite.getPublicKey();
			//解密站点发送的订单
			decodeData = RSAUtil.decryptByPublicKey(sign_value,publicKey);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException(e,false,SpringUtil.getI18nMsg("decode_val_error"));
		}
		JSONObject jsonObject = null;
		try {
			// 将字符串转为Json
			jsonObject = JSONObject.parseObject(decodeData);
		} catch (Exception e) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg",
					SpringUtil.getI18nMsg("decode_val_error"));
			return resultMap;
		}

		
		
		// 3、获取网站发起的支付方式是否已经接入
		Payment payment = paymentDao.queryPaymentBySiteIdAndPayType(webSite.getId(), FengPayContraint.B2C_GATEWAY);
		if (payment == null) {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("no_pay_type"));
			return resultMap;
		}

		UnionPayFullInfo unionPayFullInfo = null;
		// 判断用户的支付方式接入是否使用的营业执照
		if (payment.getIsFullInfo() == '1') {
			// 非营业执照接入，启动代理收款模式
			// ///加载本平台通过营业执照申请到的公钥私钥信息
			String mchID = SimpleUtil.b2CGateWayMap.get("mchID");
			String certPath = SimpleUtil.b2CGateWayMap.get("certPath");
			String mchKey = SimpleUtil.b2CGateWayMap.get("mchKey");

			unionPayFullInfo = new UnionPayFullInfo();
			unionPayFullInfo.setMchID(mchID);
			unionPayFullInfo.setMchKey(mchKey);
			unionPayFullInfo.setCertPath(certPath);

		} else
			unionPayFullInfo = unionPayFullDao.queryUnionPayFullBySiteId(webSite.getId());
		String queryDate = jsonObject.getString("billDate");
		
		resultMap = UnionPayUtil.downloadBillFile(unionPayFullInfo,queryDate);
		return resultMap;
	}

}
